<template>
  <div id="studentScoreNumByLevel">
    <div ref="chartRef" style="width: 800px; height: 600px;"></div>
    <div class="course-select">
      <span style="font-size: 18px;">课程：</span>
      <a-select  v-model:value="courseName" style="width: 150px" @change="onChange">
        <a-select-option v-for="item in courseList" :value="item.courseName" :key="item.id">{{ item.courseName }}</a-select-option>
      </a-select>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import * as echarts from 'echarts'
import { message } from 'ant-design-vue'
import { getStudentNumByLevelUsingGet } from '@/api/studentScoreController.ts'
import { listCourseUsingPost } from '@/api/courseController.ts'

const chartRef = ref(null)
let chartInstance = null

const genderData = ref()
const courseName = ref('英语')

const renderChart = () => {
  if (!chartInstance) {
    chartInstance = echarts.init(chartRef.value)
  }

  const option = {
    title: {
      text: `${courseName.value}单科成绩人数分布`,
      left: 'center'
    },
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '人数',
        type: 'pie',
        radius: '50%',
        data: [
          { value: genderData.value['A'] ?? 0, name: 'A（90~100）' },
          { value: genderData.value['B'] ?? 0, name: 'B（75~90）' },
          { value: genderData.value['C'] ?? 0, name: 'C（60~75）' },
          { value: genderData.value['D'] ?? 0, name: 'D（0~60）' },
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }

  chartInstance.setOption(option)
}

const fetchData = async () => {
  const res = await getStudentNumByLevelUsingGet({
    courseName: courseName.value
  })
  if (res.data.code === 0 && res.data.data) {
    genderData.value = res.data.data
  } else {
    message.error("获取数据失败" + res.data.message)
  }
}

const courseList = ref<API.Course[]>([])
const fetchCourseList = async () => {
  const res = await listCourseUsingPost({})
  if (res.data.code === 0 && res.data.data) {
    courseList.value = res.data.data ?? []
  } else {
    message.error('获取数据失败' + res.data.message)
  }
}

onMounted( () => {
  fetchCourseList()
  fetchData()
  // 监听窗口大小变化，防止图表不自适应
  window.addEventListener('resize', () => {
    chartInstance.resize()
  })
})

const onChange = () => {
  fetchData()
  renderChart()
}

// 如果genderData是接口动态获取的，推荐监听它重新渲染
watch(genderData, () => {
  renderChart()
})

</script>

<style scoped>
#studentScoreNumByLevel {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.course-select {
  position: absolute;
  top: 175px;
  right: 100px;
}
</style>
